/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package DataAccess;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Van Cong
 */
public class DataConnect {
    Connection connection;
    Statement statement;
    String query, dataName;
    public DataConnect(){
        dataName = "InternetManagement";
        String user = "root"; //Mặc định là root
        String pass = ""; //Mật khẩu quản trị MySQL
        String url = "jdbc:mysql://localhost/"+dataName+"?user="+user+"&password="+pass;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url);
            statement = connection.createStatement();
        }catch (Exception e){
            try { 
                connection = DriverManager.getConnection ("jdbc:mysql://localhost/", "root", "");
                statement = connection.createStatement();
                int result = statement.executeUpdate("CREATE DATABASE " + dataName);                
                if(result != 1) System.out.println("Khong tao duoc data");
                connection = DriverManager.getConnection(url);                
                statement =  connection.createStatement();
                tablesCreate();
            } catch (SQLException ex) {
                Logger.getLogger(DataConnect.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    public void connectClose(){
        try {
            statement.close();
            connection.close();
        } catch (SQLException ex) {
            Logger.getLogger(DataConnect.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public Statement getStatement(){
        return statement;
    }
    public void tablesCreate(){
         employTable();
    }
    public void employTable(){
        query = "create table employ_table( id int, primary key(id), name text, password text, address text )";        
        sqlExecute(query);        
        query = "insert into employ_table (id, name, password, address) value (0, 'admin', '123456', 'Da Nang')";       
        sqlExecute(query);
    }
    public void sqlExecute(String sql){
        try {
            boolean result = statement.execute(sql);
        } catch (SQLException ex) {
            Logger.getLogger(DataConnect.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
